<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useCategoryStore } from '@/stores/category'
import { useTransactionStore } from '@/stores/transaction'
import { transactionDB } from '@/utils/database'
import { manualCheckUpdate, getCurrentVersion } from '@/utils/appUpdate'
import { showToast, showConfirmDialog } from 'vant'

const router = useRouter()
const categoryStore = useCategoryStore()
const transactionStore = useTransactionStore()

// 当前版本号
const currentVersion = getCurrentVersion()

const onInitCategories = async () => {
  showConfirmDialog({
    title: '初始化分类',
    message: '确定要重新初始化默认分类吗？这不会影响已有分类。',
  }).then(async () => {
    try {
      await categoryStore.initializeCategories()
      showToast('初始化成功')
    } catch (error) {
      console.error('初始化分类失败:', error)
      showToast('初始化失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

const onExportData = async () => {
  try {
    // 获取所有数据
    await transactionStore.fetchTransactions({})
    await categoryStore.fetchCategories()
    
    const exportData = {
      version: '1.0.0',
      exportTime: new Date().toISOString(),
      categories: categoryStore.categories,
      transactions: transactionStore.transactions
    }
    
    // 创建JSON文件并下载
    const dataStr = JSON.stringify(exportData, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    const link = document.createElement('a')
    link.href = url
    link.download = `记账本数据_${new Date().toISOString().slice(0, 10)}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    showToast('导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    showToast('导出失败')
  }
}

const fileInput = ref<HTMLInputElement | null>(null)

const onImportData = () => {
  // 触发文件选择
  if (!fileInput.value) {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'application/json'
    input.onchange = handleFileSelect
    fileInput.value = input
  }
  fileInput.value?.click()
}

const handleFileSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  try {
    const text = await file.text()
    const data = JSON.parse(text)
    
    // 验证数据格式
    if (!data.categories || !data.transactions) {
      showToast('数据格式错误')
      return
    }
    
    showConfirmDialog({
      title: '导入数据',
      message: `确定要导入数据吗？将导入 ${data.categories.length} 个分类和 ${data.transactions.length} 条交易记录。`,
    }).then(async () => {
      // TODO: 实现数据导入逻辑
      showToast('导入功能开发中...')
    }).catch(() => {
      // 用户取消
    })
  } catch (error) {
    console.error('导入数据失败:', error)
    showToast('导入失败，请检查文件格式')
  }
}

const onClearData = () => {
  showConfirmDialog({
    title: '清除所有数据',
    message: '确定要清除所有交易记录吗？此操作不可恢复！分类数据将保留。',
    confirmButtonText: '确定清除',
    confirmButtonColor: '#ff4444',
  }).then(async () => {
    try {
      await transactionDB.deleteAll()
      showToast('清除成功')
      // 刷新交易记录
      await transactionStore.fetchTransactions()
    } catch (error) {
      console.error('清除数据失败:', error)
      showToast('清除失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

const onCheckUpdate = async () => {
  await manualCheckUpdate()
}

const onAbout = () => {
  showConfirmDialog({
    title: '关于记账本',
    message: `版本：${currentVersion}\n开发者：zhangdaye\n\n一个简洁易用的离线记账应用\n数据存储在本地，保护您的隐私\n\n感谢您的使用！`,
    confirmButtonText: '好的',
    showCancelButton: false,
  })
}
</script>

<template>
  <div class="settings-view">
    <van-nav-bar title="设置" />

    <van-cell-group inset>
      <van-cell title="分类管理" is-link @click="router.push('/categories')">
        <template #icon>
          <van-icon name="apps-o" class="cell-icon" />
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group inset title="数据管理">
      <van-cell title="初始化默认分类" is-link @click="onInitCategories">
        <template #icon>
          <van-icon name="replay" class="cell-icon" />
        </template>
      </van-cell>
      <van-cell title="导出数据" is-link @click="onExportData">
        <template #icon>
          <van-icon name="down" class="cell-icon" />
        </template>
        <template #label>
          <span class="cell-label">导出为JSON文件</span>
        </template>
      </van-cell>
      <van-cell title="导入数据" is-link @click="onImportData">
        <template #icon>
          <van-icon name="upgrade" class="cell-icon" />
        </template>
        <template #label>
          <span class="cell-label">从JSON文件导入</span>
        </template>
      </van-cell>
      <van-cell title="清除所有数据" is-link @click="onClearData">
        <template #icon>
          <van-icon name="delete-o" class="cell-icon" />
        </template>
        <template #label>
          <span class="cell-label">删除所有交易记录</span>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group inset title="关于应用">
      <van-cell title="应用名称" value="记账本">
        <template #icon>
          <van-icon name="apps-o" class="cell-icon" />
        </template>
      </van-cell>
      <van-cell title="当前版本" :value="currentVersion" is-link @click="onCheckUpdate">
        <template #icon>
          <van-icon name="info-o" class="cell-icon" />
        </template>
        <template #label>
          <span class="cell-label">点击检查更新</span>
        </template>
      </van-cell>
      <van-cell title="检查更新" is-link @click="onCheckUpdate">
        <template #icon>
          <van-icon name="upgrade" class="cell-icon" />
        </template>
        <template #label>
          <span class="cell-label">检查是否有新版本</span>
        </template>
      </van-cell>
      <van-cell title="开发者" value="zhangdaye">
        <template #icon>
          <van-icon name="user-o" class="cell-icon" />
        </template>
      </van-cell>
      <van-cell title="关于" is-link @click="onAbout">
        <template #icon>
          <van-icon name="question-o" class="cell-icon" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<style scoped>
.settings-view {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
}

.cell-icon {
  margin-right: 12px;
  font-size: 18px;
  line-height: 1;
  display: flex;
  align-items: center;
}

.cell-label {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

:deep(.van-cell-group) {
  margin: 16px;
}

:deep(.van-cell-group__title) {
  padding: 16px 16px 8px;
  color: #646566;
  font-size: 14px;
}

:deep(.van-cell) {
  padding: 12px 16px;
}

:deep(.van-cell__title) {
  display: flex;
  align-items: center;
}

:deep(.van-cell__value) {
  color: #969799;
}
</style>
